import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:p_location/common/res/common_res.dart';
import 'package:p_location/common/widget/common_app_bar.dart';
import 'package:p_location/common/widget/common_button_view.dart';
import 'package:p_location/common/widget/search_bar.dart';
import 'package:p_location/net/net_listener.dart';
import 'package:p_location/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:p_location/common/obj/page.dart' as MPage;

abstract class BaseListPage<T> extends StatefulWidget {
  final bool isFromSearch;
  final bool isHiddenAppbar;
  final bool isHiddenBack;

  BaseListPageState getState();

  @override
  BaseListPageState createState() => getState();

  const BaseListPage(
      {Key key,
      this.isFromSearch = false,
      this.isHiddenAppbar = false,
      this.isHiddenBack = false})
      : super(key: key);
}

abstract class BaseListPageState<T extends BaseListPage> extends State<T>
    with AutomaticKeepAliveClientMixin
    implements NetListener {
  bool isLoading = true;
  String keyWord;

  String errorMsg;
  int currPage = 1;
  int pageNum = 20;
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  List lists = [];

  Map<String, dynamic> params = {};

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: _getScaffold(),
    );
  }

  _getScaffold() {
    if (widget.isHiddenAppbar) {
      return Scaffold(
        body: _getContentView(),
      );
    } else {
      return Scaffold(
        appBar: widget.isFromSearch
            ? _getSearchAppBar(context)
            : _getCommonAppBar(),
        body: _getContentView(),
      );
    }
  }

  _getCommonAppBar() {
    if (widget.isHiddenBack) {
      return AppBar(
        title: new Text(getTitle()),
        actions: getActions(),
      );
    } else {
      return CommonAppBar(
        title: Text(
          getTitle(),
          style: TextStyle(color: Colors.black),
        ),
        actions: getActions(),
        onPress: () {
          Navigator.pop(context);
        },
      );
    }
  }

  _getSearchAppBar(context) {
    return SearchBar(
      hideLeft: false,
      hint: '请输入关键字',
      leftButtonClick: _pop,
      rightButtonClick: searchRefresh,
      onChanged: _onKeyWordChanged,
    );
  }

  _pop() {
    Navigator.pop(context);
  }

  void _onKeyWordChanged(String value) {
    keyWord = value;
  }

  void searchRefresh() {
    print('keyword$keyWord');
    _requestList(true);
  }

  _getContentView() {
    if (isLoading) {
      return _getLoadingView();
    }
    if (!StringUtil.isEmpty(errorMsg)) {
//      return NoResultWidget('images/img_no_accident.png', errorMsg);
      return _getRefreshView(false, errorMsg);
    }
    if ((!widget.isFromSearch || !StringUtil.isEmpty(keyWord)) &&
        (lists == null || lists.length == 0)) {
//      return NoResultWidget('images/img_no_accident.png', '暂无数据...');
      return _getRefreshView(false, '暂无数据...');
    } else {
      return _getRefreshView(true,"");
    }
  }

  _getLoadingView() {
    return Center(
      child: Image.asset('images/timg.gif'),
    );
  }

  _getRefreshView(hasData,msg) {
    return Stack(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(bottom: hasAdd() ? 60 : 0),
          child: hasData ? SmartRefresher(
            enablePullDown: false,
            enablePullUp: true,
            header: WaterDropHeader(),
            footer: CustomFooter(
              builder: (BuildContext context, LoadStatus mode) {
                Widget body;
                print(mode);
                if (mode == LoadStatus.idle) {
                  body = Text("上拉加载更多...");
                } else if (mode == LoadStatus.loading) {
                  body = CircularProgressIndicator();
                } else if (mode == LoadStatus.failed) {
                  body = Text("加载失败，点击重试...");
                } else if (mode == LoadStatus.canLoading) {
                  body = Text("上拉加载更多...");
                } else {
                  body = Text("没有更多数据了...");
                }
                return Container(
                  height: 55.0,
                  child: Center(child: body),
                );
              },
            ),
            controller: _refreshController,
//                  onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: _listView(),
          ):Container(
              alignment: Alignment.center,
              padding: EdgeInsets.only(top: 200),
              child: Stack(
                children: <Widget>[
                  Container(
                    child: Column(
//                direction: Axis.vertical,
//                crossAxisAlignment: WrapCrossAlignment.center,
                      children: <Widget>[
                        Image.asset(
//                'images/img_no_accident.png',
                          'images/img_no_accident.png',
                          scale: 2.5,
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 20, right: 20),
                          child: Text(
                            msg,
                            style: TextStyle(fontSize: 12, color: Color(0xff666666)),
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ))
        ),
        CommonButtonView(
          '新增',
          onAddClicked(),
          vanish: !hasAdd(),
        ),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    if (!widget.isFromSearch) {
      _requestList(false);
    } else {
      isLoading = false;
    }
  }

  _onLoading() {
    currPage++;
    _requestList(false);
  }

  @override
  void deactivate() {
    var bool = ModalRoute.of(context).isCurrent;
    if (needBackRefresh() && bool) {
      _requestList(true);
    }
    super.deactivate();
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  _listView() {
    return ListView.separated(
        itemBuilder: (context, index) {
          return createListViewItem(index);
        },
        separatorBuilder: (context, index) {
          return Divider(
            color: Colors.grey,
            height: 0.4,
          );
        },
        itemCount: lists.length);
  }

  _requestList(bool isRefresh) {
    if (isRefresh) {
      isLoading = true;
      currPage = 1;
      lists.clear();
    }
    if (getSearchKey() != null && keyWord != null) {
      params[getSearchKey()] = keyWord;
    }
    MPage.Page page = MPage.Page(currPage, pageNum);
    params['page'] = json.decode(page.toJson());
    realRequest();
  }

  @override
  void onRequestSuccess(Response response) {
    print('onRequestSuccess');
    setState(() {
      isLoading = false;
      if (response != null && response.data != null) {
        if (currPage == 0) {
          lists.clear();
        }
        lists.addAll(getList(response));
      }
      print("hasNextPage()===" + hasNextPage().toString());
      if (hasNextPage()) {
        _refreshController.loadNoData();
      } else {
        _refreshController.loadComplete();
      }
    });
  }

  @override
  void onRequestError(CommonRes errorRes) {
    print('onRequestError');
    if (errorRes != null) {
      setState(() {
        isLoading = false;
        errorMsg = errorRes.msg;
      });
    }
  }

  @override
  bool get wantKeepAlive => true;

  // 获取页面标题
  String getTitle();

  List<Widget> getActions();

  // 子页面重写
  String getSearchKey() {
    return null;
  }

  // 创建列表项
  createListViewItem(index);

  // 请求
  void realRequest();

  // 请求成功后 转化为相应list
  List getList(response);

  // 分页是否有下一页
  bool hasNextPage();

  bool hasAdd() {
    return false;
  }

  void addEvent() {
    print('addEvent');
  }

  onAddClicked() {
    return () {
      print('点击新增');
      addEvent();
    };
  }

  bool needBackRefresh() {
    return false;
  }
}
